package org.chen.flight.service.flight;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.flight.*;
import org.chen.common.flight.request.FlightSearchRequest;
import org.chen.common.flight.response.OneWayFlightSearchResponse;
import org.chen.common.flight.response.RoundTripFlightSearchResponse;
import org.chen.flight.feign.BaiDuTranslateClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * 机票搜索核心服务
 * 负责搜索流程的编排和协调
 */
@Service
@Slf4j
public class FlightSearchService {

    @Autowired
    private FlightApiService flightApiService;

    @Autowired
    private OneWayFlightProcessService oneWayProcessService;

    @Autowired
    private RoundTripFlightProcessService roundTripProcessService;
    
    @Autowired
    private FlightDataService flightDataService;

    /**
     * 搜索单程机票
     */
    public OneWayFlightSearchResponse searchOneWayFlights(FlightSearchRequest request) {
        try {
            log.info("开始单程航班搜索，路线: {}-{}, 语言: {}",
                    request.getDeparture(), request.getDestination(), request.getLang());

            return searchOneWayFlightsInternal(request);
        } catch (Exception e) {
            log.error("搜索单程机票失败", e);
            return OneWayFlightSearchResponse.error("搜索机票失败: " + e.getMessage());
        }
    }

    /**
     * 搜索往返机票
     */
    public RoundTripFlightSearchResponse searchRoundTripFlights(FlightSearchRequest request) {
        try {
            return searchRoundTripFlightsInternal(request);
        } catch (Exception e) {
            log.error("搜索往返机票失败", e);
            return RoundTripFlightSearchResponse.error("搜索机票失败: " + e.getMessage());
        }
    }

    /**
     * 单程搜索内部实现
     */
    private OneWayFlightSearchResponse searchOneWayFlightsInternal(FlightSearchRequest request) {
        // 第一步：获取transactionID和基础数据
        FlightSearchData searchData = flightApiService.getTransactionData(request);

        // 第二步：使用搜索数据获取详细机票价格
        OneWayFlightSearchResponse response = flightApiService.getFlightDetailsOneWayRaw(searchData, request);

        // 第三步：处理和过滤数据
        if (response.isSuccess() && response.getFlights() != null && !response.getFlights().isEmpty()) {
            // 3.1 基础数据处理（筛选、去重、排序等，不包含翻译）
            List<OneWayFlightInfo> processedFlights = oneWayProcessService.processFlights(
                    response.getFlights(), request);
            log.info("基础处理完成，数量: {}", processedFlights.size());

            // 3.2 保存到数据库
            List<OneWayFlightInfo> savedFlights = flightDataService.saveOneWayFlightsToDatabase(
                    processedFlights, searchData.getTransactionID(), request);
//            log.info("数据保存完成，数量: {}", savedFlights.size());

            // 3.3 处理多语言翻译
            List<OneWayFlightInfo> finalFlights = oneWayProcessService.processFlightsWithTranslation(
                    savedFlights, request);
            log.info("多语言处理完成，最终数量: {}", finalFlights.size());

            // 3.4 设置最终结果
            response.setFlights(finalFlights);
            response.setTotalCount(finalFlights.size());
        }

        return response;
    }

    /**
     * 往返搜索内部实现
     */
    private RoundTripFlightSearchResponse searchRoundTripFlightsInternal(FlightSearchRequest request) {
        // 第一步：获取transactionID和基础数据
        FlightSearchData searchData = flightApiService.getTransactionData(request);

        // 第二步：使用搜索数据获取详细机票价格
        RoundTripFlightSearchResponse response = flightApiService.getFlightDetailsRoundTripRaw(searchData, request);

        // 第三步：处理和过滤数据
        if (response.isSuccess() && response.getFlights() != null && !response.getFlights().isEmpty()) {
            // 3.1 基础数据处理（筛选、去重、排序等，不包含翻译）
            List<RoundTripFlightInfo> processedFlights = roundTripProcessService.processFlights(response.getFlights(), request);

            // 3.2 保存到数据库
            List<RoundTripFlightInfo> savedFlights = flightDataService.saveRoundTripFlightsToDatabase(
                    processedFlights, searchData.getTransactionID(), request);
//            log.info("数据保存完成，数量: {}", savedFlights.size());

            // 3.3 处理多语言翻译
            List<RoundTripFlightInfo> finalFlights = roundTripProcessService.processFlightsWithTranslation(
                    savedFlights, request);
            log.info("多语言处理完成，最终数量: {}", finalFlights.size());

            // 3.4 设置最终结果
            response.setFlights(finalFlights);
            response.setTotalCount(finalFlights.size());
        }

        return response;
    }
}